
/*
SoftwareSerial.cpp (formerly NewSoftSerial.cpp) -
Multi-instance software serial library for Arduino/Wiring
-- Interrupt-driven receive and other improvements by ladyada
(http://ladyada.net)
-- Tuning, circular buffer, derivation from class Print/Stream,
multi-instance support, porting to 8MHz processors,
various optimizations, PROGMEM delay tables, inverse logic and
direct port writing by Mikal Hart (http://www.arduiniana.org)
-- Pin change interrupt macros by Paul Stoffregen (http://www.pjrc.com)
-- 20MHz processor support by Garrett Mace (http://www.macetech.com)
-- ATmega1280/2560 support by Brett Hagman (http://www.roguerobotics.com/)
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
The latest version of this library can always be found at
http://arduiniana.org.
*/
// When set, _DEBUG co-opts pins 11 and 13 for debugging with an
// oscilloscope or logic analyzer. Beware: it also slightly modifies
// the bit times, so don't rely on it too much at high baud rates
#define _DEBUG 0
#define _DEBUG_PIN1 11
#define _DEBUG_PIN2 13
//
// Includes
//
#include <avr/interrupt.h>
#include <avr/pgmspace.h>
#include <Arduino.h>
#include <Serial.h>
//
// Lookup table
//
typedef struct _DELAY_TABLE
{
long baud;
unsigned short rx_delay_centering;
unsigned short rx_delay_intrabit;
unsigned short rx_delay_stopbit;
unsigned short tx_delay;
} DELAY_TABLE;

#if F_CPU == 16000000

static const DELAY_TABLE PROGMEM table[] =
{
// baud rxcenter rxintra rxstop tx
{ 115200, 1, 17, 17, 12, },
{ 57600, 10, 37, 37, 33, },
{ 38400, 25, 57, 57, 54, },
{ 31250, 31, 70, 70, 68, },
{ 28800, 34, 77, 77, 74, },
{ 19200, 54, 117, 117, 114, },
{ 14400, 74, 156, 156, 153, },
{ 9600, 114, 236, 236, 233, },
{ 4800, 233, 474, 474, 471, },
{ 2400, 471, 950, 950, 947, },
{ 1200, 947, 1902, 1902, 1899, },
{ 600, 1902, 3804, 3804, 3800, },
{ 300, 3804, 7617, 7617, 7614, },
};
const int XMIT_START_ADJUSTMENT = 5;

#elif F_CPU == 8000000

static const DELAY_TABLE table[] PROGMEM =
{
// baud rxcenter rxintra rxstop tx
{ 115200, 1, 5, 5, 3, },
{ 57600, 1, 15, 15, 13, },
{ 38400, 2, 25, 26, 23, },
{ 31250, 7, 32, 33, 29, },
{ 28800, 11, 35, 35, 32, },
{ 19200, 20, 55, 55, 52, },
{ 14400, 30, 75, 75, 72, },
{ 9600, 50, 114, 114, 112, },
{ 4800, 110, 233, 233, 230, },
{ 2400, 229, 472, 472, 469, },
{ 1200, 467, 948, 948, 945, },
{ 600, 948, 1895, 1895, 1890, },
{ 300, 1895, 3805, 3805, 3802, },
};
const int XMIT_START_ADJUSTMENT = 4;

#elif F_CPU == 20000000

// 20MHz support courtesy of the good people at macegr.com.
// Thanks, Garrett!
static const DELAY_TABLE PROGMEM table[] =
{
// baud rxcenter rxintra rxstop tx
{ 115200, 3, 21, 21, 18, },
{ 57600, 20, 43, 43, 41, },
{ 38400, 37, 73, 73, 70, },
{ 31250, 45, 89, 89, 88, },
{ 28800, 46, 98, 98, 95, },
{ 19200, 71, 148, 148, 145, },
{ 14400, 96, 197, 197, 194, },
{ 9600, 146, 297, 297, 294, },
{ 4800, 296, 595, 595, 592, },
{ 2400, 592, 1189, 1189, 1186, },
{ 1200, 1187, 2379, 2379, 2376, },
{ 600, 2379, 4759, 4759, 4755, },
{ 300, 4759, 9523, 9523, 9520, },
};

const int XMIT_START_ADJUSTMENT = 6;

#else
#error This version of SoftwareSerial supports only 20, 16 and 8MHz processors
#endif
//
// Statics
//
static Serial_t * active_object = NULL;

static char _receive_buffer[_SS_MAX_RX_BUFF];

static volatile uint8_t _receive_buffer_tail = 0;
static volatile uint8_t _receive_buffer_head = 0;

// ==========================================================================
//   DebugPulse
// 
//   This function generates a brief pulse
//   for debugging or measuring on an oscilloscope.
// ==========================================================================
inline void DebugPulse (uint8_t pin, uint8_t count)
{
#if _DEBUG
  volatile uint8_t *pport = portOutputRegister(digitalPinToPort(pin));
  uint8_t val = *pport;
  while (count--) {
    *pport = val | digitalPinToBitMask(pin);
    *pport = val;
  }
#endif
}

//
// Private methods
//

// ==========================================================================
//   tunedDelay
// ==========================================================================
static inline void tunedDelay (uint16_t delay) 
{
  uint8_t tmp=0;
  asm volatile("sbiw %0, 0x01 \n\t"
	       "ldi %1, 0xFF \n\t"
	       "cpi %A0, 0xFF \n\t"
	       "cpc %B0, %1 \n\t"
	       "brne .-10 \n\t"
	       : "+r" (delay), "+a" (tmp)
	       : "0" (delay)
	       );
}

// ==========================================================================
//   Serial_listen
//
//   This function sets the current object as the "listening"
//   one and returns true if it replaces another
// ==========================================================================
int Serial_listen (Serial_t * this)
{
  if (active_object != this) {
    this->_buffer_overflow = false;
    uint8_t oldSREG = SREG;
    cli();
    _receive_buffer_head = _receive_buffer_tail = 0;
    active_object = this;
    SREG = oldSREG;
    return 1;
  }
  return 0;
}

// ==========================================================================
//   tx_pin_write
// ==========================================================================
static void tx_pin_write (Serial_t * this, uint8_t pin_state)
{
  if (pin_state == LOW)
    *this->_transmitPortRegister &= ~this->_transmitBitMask;
  else
    *this->_transmitPortRegister |= this->_transmitBitMask;
}

// ==========================================================================
//   tx_pin_read
// ==========================================================================
static uint8_t rx_pin_read (Serial_t * this)
{
  return *this->_receivePortRegister & this->_receiveBitMask;
}

// ==========================================================================
//   Serial_recv
//
//   The receive routine called by the interrupt handler
// ==========================================================================
void Serial_recv (Serial_t * this)
{
#if GCC_VERSION < 40302
  // Work-around for avr-gcc 4.3.0 OSX version bug
  // Preserve the registers that the compiler misses
  // (courtesy of Arduino forum user *etracer*)
  asm volatile(
	       "push r18 \n\t"
	       "push r19 \n\t"
	       "push r20 \n\t"
	       "push r21 \n\t"
	       "push r22 \n\t"
	       "push r23 \n\t"
	       "push r26 \n\t"
	       "push r27 \n\t"
	       ::);
#endif

  uint8_t i;
  uint8_t d = 0;
  // If RX line is high, then we don't see any start bit
  // so interrupt is probably not for us
  if (this->_inverse_logic ? rx_pin_read(this) : !rx_pin_read(this)) {
    // Wait approximately 1/2 of a bit width to "center" the sample
    tunedDelay(this->_rx_delay_centering);
    DebugPulse(_DEBUG_PIN2, 1);
    // Read each of the 8 bits
    for (i = 0x1; i; i <<= 1) {
      tunedDelay(this->_rx_delay_intrabit);
      DebugPulse(_DEBUG_PIN2, 1);
      uint8_t noti = ~i;
      if (rx_pin_read(this))
	d |= i;
      else // else clause added to ensure function timing is ~balanced
	d &= noti;
    }

    // skip the stop bit
    tunedDelay(this->_rx_delay_stopbit);
    DebugPulse(_DEBUG_PIN2, 1);
    if (this->_inverse_logic)
      d = ~d;

    // if buffer full, set the overflow flag and return
    if ((_receive_buffer_tail + 1) % _SS_MAX_RX_BUFF != _receive_buffer_head) {
      // save new data in buffer: tail points to where byte goes
      _receive_buffer[_receive_buffer_tail] = d; // save new byte
      _receive_buffer_tail = (_receive_buffer_tail + 1) % _SS_MAX_RX_BUFF;
    }
    else {
#if _DEBUG // for scope: pulse pin as overflow indictator
      DebugPulse(_DEBUG_PIN1, 1);
#endif
      this->_buffer_overflow = true;
    }
  }

#if GCC_VERSION < 40302
  // Work-around for avr-gcc 4.3.0 OSX version bug
  // Restore the registers that the compiler misses
  asm volatile(
	       "pop r27 \n\t"
	       "pop r26 \n\t"
	       "pop r23 \n\t"
	       "pop r22 \n\t"
	       "pop r21 \n\t"
	       "pop r20 \n\t"
	       "pop r19 \n\t"
	       "pop r18 \n\t"
	       ::);
#endif
}

// ==========================================================================
// Interrupt handling
// ==========================================================================
static inline void handle_interrupt ()
{
  if (active_object) {
    Serial_recv(active_object);
  }
}

#if defined(PCINT0_vect)
ISR(PCINT0_vect) {
  handle_interrupt();
}
#endif
#if defined(PCINT1_vect)
ISR(PCINT1_vect) {
  handle_interrupt();
}
#endif
#if defined(PCINT2_vect)
ISR(PCINT2_vect) {
  handle_interrupt();
}
#endif
#if defined(PCINT3_vect)
ISR(PCINT3_vect) {
  handle_interrupt();
}
#endif

#if 0
// ==========================================================================
//   Serial_constructor
// ==========================================================================
void Serial_constructor (
  Serial_t * this, 
  uint8_t receivePin, 
  uint8_t transmitPin, 
  bool inverse_logic /* = false */
)
{
  serial->_rx_delay_centering = 0;
  serial->_rx_delay_intrabit = 0;
  serial->_rx_delay_stopbit = 0;
  serial->_tx_delay = 0;
  serial->_buffer_overflow = false;
  serial->_inverse_logic = inverse_logic;

  setTX(transmitPin);
  setRX(receivePin);
}

// ==========================================================================
//   Serial_destructor
// ==========================================================================
void Serial_destructor (Serial_t * this)
{
  end(this);
}
#endif // 0

// ==========================================================================
//   setTX
// ==========================================================================
static void setTX (Serial_t * this, uint8_t tx)
{
  pinMode(tx, OUTPUT);
  digitalWrite(tx, this->_inverse_logic ? LOW : HIGH);
  this->_transmitBitMask = digitalPinToBitMask(tx);
  uint8_t port = digitalPinToPort(tx);
  this->_transmitPortRegister = portOutputRegister(port);
}

// ==========================================================================
//   setRX
// ==========================================================================
static void setRX (Serial_t * this, uint8_t rx)
{
  pinMode(rx, INPUT);
  if (!this->_inverse_logic) {
    digitalWrite(rx, HIGH); // pullup for normal logic!
  }
  this->_receivePin = rx;
  this->_receiveBitMask = digitalPinToBitMask(rx);
  uint8_t port = digitalPinToPort(rx);
  this->_receivePortRegister = portInputRegister(port);
}

// ==========================================================================
//   Serial_begin
// ==========================================================================
void Serial_begin (
  Serial_t * this, 
  uint8_t receivePin, 
  uint8_t transmitPin, 
  int inverse_logic /* = false */,
  long speed
)
{
  unsigned i;

  this->_rx_delay_centering = 0;
  this->_rx_delay_intrabit = 0;
  this->_rx_delay_stopbit = 0;
  this->_tx_delay = 0;
  
  this->_buffer_overflow = 0;
  this->_inverse_logic = inverse_logic;

  setTX(this, transmitPin);
  setRX(this, receivePin);

  for (i = 0; i < sizeof(table)/sizeof(table[0]); ++i) {
    long baud = pgm_read_dword(&table[i].baud);
    if (baud == speed) {
      this->_rx_delay_centering = pgm_read_word(&table[i].rx_delay_centering);
      this->_rx_delay_intrabit = pgm_read_word(&table[i].rx_delay_intrabit);
      this->_rx_delay_stopbit = pgm_read_word(&table[i].rx_delay_stopbit);
      this->_tx_delay = pgm_read_word(&table[i].tx_delay);
      break;
    }
  }

  // Set up RX interrupts, but only if we have a valid RX baud rate
  if (this->_rx_delay_stopbit) {
    uint8_t _receivePin = this->_receivePin;
    if (digitalPinToPCICR(_receivePin)) {
      *digitalPinToPCICR(_receivePin) |= _BV(digitalPinToPCICRbit(_receivePin));
      *digitalPinToPCMSK(_receivePin) |= _BV(digitalPinToPCMSKbit(_receivePin));
    }
    tunedDelay(this->_tx_delay); // if we were low this establishes the end
  }
#if _DEBUG
  pinMode(_DEBUG_PIN1, OUTPUT);
  pinMode(_DEBUG_PIN2, OUTPUT);
#endif
  Serial_listen(this);
}

// ==========================================================================
//   Serial_end
// ==========================================================================
void Serial_end (Serial_t * this)
{
  uint8_t _receivePin = this->_receivePin;
  if (digitalPinToPCMSK(_receivePin))
    *digitalPinToPCMSK(_receivePin) &= ~_BV(digitalPinToPCMSKbit(_receivePin));
}

// ==========================================================================
//   Serial_read
//
//   Read data from buffer
// ==========================================================================
int Serial_read (Serial_t * this)
{
  if (!Serial_isListening(this))
    return -1;
  // Empty buffer?
  if (_receive_buffer_head == _receive_buffer_tail)
    return -1;
  // Read from "head"
  uint8_t d = _receive_buffer[_receive_buffer_head]; // grab next byte
  _receive_buffer_head = (_receive_buffer_head + 1) % _SS_MAX_RX_BUFF;
  return d;
}

// ==========================================================================
//   Serial_available
// ==========================================================================
int Serial_available (Serial_t * this)
{
  if (!Serial_isListening(this))
    return 0;

  return (_receive_buffer_tail + _SS_MAX_RX_BUFF - _receive_buffer_head) % _SS_MAX_RX_BUFF;
}

// ==========================================================================
//   Serial_isListening
// ==========================================================================
int Serial_isListening (Serial_t * this) 
{ 
  return (this == active_object ? 1 : 0); 
}

// ==========================================================================
//   Serial_setWriteError
// ==========================================================================
void Serial_setWriteError (Serial_t * this, int err) 
{ 
  this->_write_error = err; 
}

// ==========================================================================
//   Serial_setWriteError
// ==========================================================================
int Serial_getWriteError (Serial_t * this) 
{ 
  return this->_write_error; 
}

// ==========================================================================
//   Serial_overflow
// ==========================================================================
int Serial_overflow (Serial_t * this) 
{ 
  int ret = this->_buffer_overflow; 
  this->_buffer_overflow = 0; 
  return ret; 
}

// ==========================================================================
//   Serial_write
// ==========================================================================
size_t Serial_write (Serial_t * this, uint8_t b)
{
  if (this->_tx_delay == 0) {
    Serial_setWriteError(this, 1);
    return 0;
  }

  uint16_t _tx_delay = this->_tx_delay;
  byte mask;
  uint8_t oldSREG = SREG;
  cli(); // turn off interrupts for a clean txmit
  // Write the start bit
  tx_pin_write(this, this->_inverse_logic ? HIGH : LOW);
  tunedDelay(_tx_delay + XMIT_START_ADJUSTMENT);

  // Write each of the 8 bits
  if (this->_inverse_logic) {
    for (mask = 0x01; mask; mask <<= 1) {
      if (b & mask) // choose bit
	tx_pin_write(this, LOW); // send 1
      else
	tx_pin_write(this, HIGH); // send 0
      tunedDelay(_tx_delay);
    }
    tx_pin_write(this, LOW); // restore pin to natural state
  }
  else {
    for (mask = 0x01; mask; mask <<= 1) {
      if (b & mask) // choose bit
	tx_pin_write(this, HIGH); // send 1
      else
	tx_pin_write(this, LOW); // send 0
      tunedDelay(_tx_delay);
    }
    tx_pin_write(this, HIGH); // restore pin to natural state
  }

  SREG = oldSREG; // turn interrupts back on
  tunedDelay(_tx_delay);
  return 1;
}

// ==========================================================================
//   Serial_flush
// ==========================================================================
void Serial_flush (Serial_t * this)
{
  if (!Serial_isListening(this))
    return;

  uint8_t oldSREG = SREG;
  cli();
  _receive_buffer_head = _receive_buffer_tail = 0;
  SREG = oldSREG;
}

// ==========================================================================
//   Serial_peek
// ==========================================================================
int Serial_peek (Serial_t * this)
{
  if (!Serial_isListening(this))
    return -1;

  // Empty buffer?
  if (_receive_buffer_head == _receive_buffer_tail)
    return -1;
  // Read from "head"
  return _receive_buffer[_receive_buffer_head];
}

// ==========================================================================
//   Serial_print_char
// ==========================================================================
size_t Serial_print_char (Serial_t * this, char c)
{
  return Serial_write(this, c);
}

// ==========================================================================
//   Serial_println
// ==========================================================================
size_t Serial_println (Serial_t * this)
{
  size_t n = Serial_print_char (this, '\r');
  n += Serial_print_char (this, '\n');
  return n;
}

// ==========================================================================
//   Serial_println_char
// ==========================================================================
size_t Serial_println_char (Serial_t * this, char c)
{
  size_t n = Serial_print_char (this, c);
  n += Serial_println (this);
  return n;
}

// ==========================================================================
//   Serial_write_string
// ==========================================================================
static size_t Serial_write_string (
  Serial_t * this, 
  const uint8_t * buffer, 
  size_t size
)
{
  size_t n = 0;
  while (size--) {
    n += Serial_write(this, *buffer++);
  }
  return n;
}

// ==========================================================================
//   Serial_print_string
// ==========================================================================
size_t Serial_print_string (Serial_t * this, const char * str)
{
  //return write(str);
  size_t len = strlen(str);
  return Serial_write_string(this, (const uint8_t *)str, len);
}

// ==========================================================================
//   Serial_println_string
// ==========================================================================
size_t Serial_println_string (Serial_t * this, const char * str)
{
  size_t n = Serial_print_string (this, str);
  n += Serial_println (this);
  return n;
}

// ==========================================================================
//   Serial_print_number
// ==========================================================================
static size_t Serial_print_number (
  Serial_t * this, 
  unsigned long n, 
  uint8_t base
) 
{
  char buf[8 * sizeof(long) + 1]; // Assumes 8-bit chars plus zero byte.
  char *str = &buf[sizeof(buf) - 1];
  *str = '\0';
  // prevent crash if called with base == 1
  if (base < 2) base = 10;
  do {
    unsigned long m = n;
    n /= base;
    char c = m - base * n;
    *--str = c < 10 ? c + '0' : c + 'A' - 10;
  } while(n);

  return Serial_print_string (this, str);
}

// ==========================================================================
//   Serial_print_signed
// ==========================================================================
size_t Serial_print_signed (Serial_t * this, long n, int base)
{
  if (base == 0) {
    return Serial_print_string (this, "??");
  } 
  else if (base == 10) {
    if (n < 0) {
      int t = Serial_print_char (this, '-');
      n = -n;
      return Serial_print_number(this, n, 10) + t;
    }
    return Serial_print_number(this, n, 10);
  } 
  else {
    return Serial_print_number(this, n, base);
  }
}

// ==========================================================================
//   Serial_println_signed
// ==========================================================================
size_t Serial_println_signed (Serial_t * this, long num, int base)
{
  size_t n = Serial_print_signed (this, num, base);
  n += Serial_println (this);
  return n;
}

// ==========================================================================
//   Serial_print_unsigned
// ==========================================================================
size_t Serial_print_unsigned (Serial_t * this, unsigned long n, int base)
{
  if (base == 0) 
    return Serial_print_string(this, "??");
  else 
    return Serial_print_number(this, n, base);
}

// ==========================================================================
//   Serial_println_unsigned
// ==========================================================================
size_t Serial_println_unsigned (Serial_t * this, unsigned long num, int base)
{
  size_t n = Serial_print_unsigned (this, num, base);
  n += Serial_println (this);
  return n;
}

// ==========================================================================
//   Serial_print_float
// ==========================================================================
size_t Serial_print_float (Serial_t * this, double number, uint8_t digits)
{
  uint8_t i;
  size_t n = 0;

  if (isnan(number)) return Serial_print_string (this, "nan");
  if (isinf(number)) return Serial_print_string (this, "inf");
  if (number > 4294967040.0) return Serial_print_string (this, "ovf"); // constant determined empirically
  if (number <-4294967040.0) return Serial_print_string (this, "ovf"); // constant determined empirically

  // Handle negative numbers
  if (number < 0.0) {
    n += Serial_print_char(this, '-');
    number = -number;
  }

  // Round correctly so that print(1.999, 2) prints as "2.00"
  double rounding = 0.5;
  for (i = 0; i < digits; ++i) {
    rounding /= 10.0;
  }

  number += rounding;
  // Extract the integer part of the number and print it
  unsigned long int_part = (unsigned long)number;
  double remainder = number - (double)int_part;
  //n += print(int_part);
  n += Serial_print_number (this, int_part, DEC);

  // Print the decimal point, but only if there are digits beyond
  if (digits > 0) {
    n += Serial_print_string (this, ".");
  }

  // Extract digits from the remainder one at a time
  while (digits-- > 0) {
    int toPrint;
    remainder *= 10.0;
    //
    // Figure out ...
    //
    //toPrint = int(remainder);
    toPrint = (int)remainder;
    n += Serial_print_signed (this, toPrint, DEC);
    remainder -= toPrint;
  }
  return n;
}

// ==========================================================================
//   Serial_println_float
// ==========================================================================
size_t Serial_println_float (Serial_t * this, double num, uint8_t digits)
{
  size_t n = Serial_print_float (this, num, digits);
  n += Serial_println (this);
  return n;
}
